package xyz.weizhi.rjwm.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import xyz.weizhi.rjwm.entity.vo.R;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * @Author milian
 * @Date 2021/9/25 0025 18:36
 */
@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {
    @Value("${image.basePath}")
    private String basePath;
    /**
     * @Author milian
     * @Description //上传
     * @Date 18:46 2021/9/25 0025
     * @Param []
     * @return xyz.weizhi.rjwm.entity.vo.R<java.lang.String>
     **/
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        //获取源文件名
        String originalFilename = file.getOriginalFilename();
        //获取源文件名文件后缀
        String Suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用UUID随机生成文件名
        String fileName = UUID.randomUUID().toString()+Suffix;
        File dir = new File(basePath);
        if (!dir.exists()){
            dir.mkdirs();
        }
        try {
            //将暂存文件转存至目标目录
            file.transferTo(new File(basePath+fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }
    /**
     * @Author milian
     * @Description //下载
     * @Date 18:47 2021/9/25 0025
     * @Param []
     * @return xyz.weizhi.rjwm.entity.vo.R<java.lang.String>
     **/
    @GetMapping("/download")
    public void download(@RequestParam("name") String fileName, HttpServletResponse response){
        try {
            //读取图片
            FileInputStream fis = new FileInputStream(new File(basePath + fileName));
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");
            byte[] bytes = new byte[1024];
            int len;
            while ((len = fis.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            fis.close();
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
